//
//  WTFDropDownView.m
//  Courses
//
//  Created by xxx on 1/17/15.
//  Copyright (c) 2015 wtf. All rights reserved.
//

#import "WTFDropDownView.h"

@implementation WTFDropDownView
{
    UIControl   *_overlayView;
    
    CGRect      _rectOriginal;
    
    CGRect      _rectToHide;
}

- (id)initWithFrame:(CGRect)frame lineToHide:(CGRect)line contentView:(UIView *)contentView
{
    self = [self initWithFrame:frame contentView:contentView];
    _rectToHide = line;
    
    return self;
}

- (id)initWithFrame:(CGRect)frame contentView:(UIView *)contentView
{
    if (self = [super initWithFrame:frame])
    {
        self.clipsToBounds = YES;
        self.hidden = YES;
        self.folded = YES;
        _rectOriginal = frame;
        [self addContentView:contentView];
    }
    return self;
}

- (void)addContentView:(UIView *)contentView
{
    self.backgroundColor = [UIColor whiteColor];
    
    CGRect contentViewFrame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
    _contentView = contentView;
    _contentView.frame = contentViewFrame;
    [self addSubview:_contentView];
    
    _overlayView = [[UIControl alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    _overlayView.backgroundColor = [UIColor colorWithRed:.16 green:.17 blue:.21 alpha:.5];
    [_overlayView addTarget:self
                     action:@selector(dismiss)
           forControlEvents:UIControlEventTouchUpInside];

}

- (void)setContentView:(UIView *)contentView
{
    _contentView = contentView;
    [self setNeedsLayout];
}

#pragma mark - animations

- (void)fadeIn
{
    //    self.transform = CGAffineTransformMakeScale(1.3, 1.3);
    
    self.alpha = 0;
    self.hidden = NO;
//    self.frame = CGRectMake(_rectOriginal.origin.x, AutoFloat(-1000), _rectOriginal.size.width, _rectOriginal.size.height);
    self.frame = _rectToHide;
    [UIView animateWithDuration:.35 animations:^{
        self.alpha = 1;
        self.frame = _rectOriginal;
        //        self.transform = CGAffineTransformMakeScale(1, 1);
    }];
    
}
- (void)fadeOut
{
    [UIView animateWithDuration:.35 animations:^{
//        self.frame = CGRectMake(_rectOriginal.origin.x, AutoFloat(-1000), _rectOriginal.size.width, _rectOriginal.size.height);
        self.frame = _rectToHide;
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        if (finished) {
            self.hidden = YES;
            [_overlayView removeFromSuperview];
            [self removeFromSuperview];
        }
    }];
}

- (void)toggle
{
    _folded ? [self show] : [self dismiss];
}

- (void)show
{
    UIWindow *keywindow = [[UIApplication sharedApplication] keyWindow];
    [keywindow addSubview:_overlayView];
    [keywindow addSubview:self];
    [self fadeIn];
    _folded = NO;
}

- (void)dismiss
{
    [self fadeOut];
    _folded = YES;
}

@end
